/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TextInput,
  Platform,
  TouchableOpacity,
  View,
  Modal,
  ListView,
  Dimensions
} from 'react-native';

import CheckBox from 'react-native-checkbox';

let windowHeight = Dimensions.get('window').height;

//textContent:提示文字，textContentStyle:提示样式
//data：传入的多选数据,listCheckBoxStyle:多选数据样式
//checkedImage:选中样式图片，uncheckedImage:未选中样式图片
//titleText:多选modal提示,titleTextStyle:多选提示样式
//horizontalLineStyle:多选modal分割线样式
//single:是否单选
//isCheckStyle:被选中的字体样式，unCheckStyle未选中的字体样式
let _this;
var ds;
//传入数据格式
// row:[
// {id: '', text:''},
// {id: '', text:''},
// {id: '', text:''},
// {id: '', text:''},
// {id: '', text:''},
// {id: '', text:''},
// ]
export default class ListCheckbox extends Component {


  constructor(props, context) {
    super(props, context);
    ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
    this.state = {
      dataSource: [],
      show: false,
      textContent: this.props.textContent ? this.props.textContent : '请选择',
      initTextContent: this.props.textContent ? this.props.textContent : '请选择',
      titleText: this.props.titleText ? this.props.titleText : '请选择',
      data: '',
      rows: [],//组合后数据
      oldRows: [],//上一次确定保存的数据，用于取消还原选项
      checkedText: [],
      selected: [],//被选中项
      single: this.props.single != null ? this.props.single : true,//是否单选
      preIndex: -1,//上一次选中项的下表标
      isCheckStyle: this.props.isCheckStyle != null ? this.props.isCheckStyle: {},
      unCheckStyle: this.props.unCheckStyle != null ? this.props.unCheckStyle: {},
    };
    this.state.dataSource = ds.cloneWithRows(this._showRows());

    _this = this;
  }

  refresh() {
    this.setState({
      dataSource: ds.cloneWithRows(this._showRows())
    });
  }

  _showRows() {
    this.state.rows = [];
    this.state.data = this.props.data;
    for (let i = 0; i < this.state.data.length; i++) {
      this.state.rows.push({ id: this.state.data[i].id, text: this.state.data[i].text, isCheck: false });
    }
    // alert(JSON.stringify(this.props.data))
    return this.state.rows;
    //return [];
  }

  _onSelected(rowData, sectionID, rowID, c) {
    if (this.state.single) {
      if (this.state.preIndex > -1) {
        this.state.rows[this.state.preIndex].isCheck = false;
      }
      this.state.preIndex = rowID;
      this.state.rows[rowID].isCheck = !c;

    } else {
      let oldAry = [...this.state.rows];
      let index = oldAry.indexOf(rowData);
      // 对旧数据中的值进行更新
      let newRow = Object.assign({}, rowData, {
        isCheck: !c
      });
      let newAry = [...oldAry.slice(0, index), newRow, ...oldAry.slice(index + 1)];
      this.state.rows = newAry;
    }

    //更新dataSource
    this.setState({
      dataSource: ds.cloneWithRows(this.state.rows)
    })
  }

  _getSelected() {
    return this.state.selected;
  }

  _renderRow(rowData, sectionID, rowID, highlightRow) {
    return (
      <View style={{ marginHorizontal: 4 }}>
        <CheckBox
          label={rowData.text}
          checked={rowData.isCheck}
          checkedImage={_this.props.checkedImage == null ? require('../images/checkbox.png') : _this.props.checkedImage}
          uncheckedImage={_this.props.uncheckedImage == null ? require('../images/uncheckbox.png') : _this.props.uncheckedImage}
          onChange={(c) => _this._onSelected(rowData, sectionID, rowID, c)}
          checkboxStyle={{ width: 15, height: 15 }} 
          labelStyle={rowData.isCheck ? _this.state.isCheckStyle:_this.state.unCheckStyle }
          />
      </View>
    )
    //<Check onSelected={_this._onSelected} sectionID={sectionID} rowID={rowID} value={rowData + '=>' + sectionID + '=>' + rowID + '=>'} />;
  }
  //每行下面加分割线
  // _renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
  //     return (
  //       <View key={`{sectionID}-${rowID}`}
  //         style={{height: 0.5, backgroundColor: 'black'}}>
  //       </View>
  //     );
  //   }




  _onCancel() {
    this.state.rows = this.state.oldRows;
    this.setState({
      show: false,
      dataSource: ds.cloneWithRows(this.state.oldRows)
    })
  }

  _onShow() {
    this.state.oldRows = this.state.rows;
    this.setState({
      show: true
    })

    if (this.props.onLoad) {
      this.props.onLoad();
    }
  }

  _onChoose() {
    this.state.selected = [];
    let isRow = [];
    for (let i = 0; i < this.state.rows.length; i++) {
      if (this.state.rows[i].isCheck == true) {
        isRow.push(this.state.rows[i].text);
        this.state.selected.push({ 'id': this.state.rows[i].id, 'text': this.state.rows[i].text });
      }
    }
    this.state.checkedText = isRow;

    this.setState({
      show: false,
      textContent: this.state.checkedText.length == 0 ? this.state.initTextContent : this.state.checkedText.join(","),
    })
    if (this.props.confirm) {
      this.props.confirm();
    }
  }
  //重置为单选或多选
  _onReset(single) {
    this.setState({
      single:single
    })
    //多选=>单选
    if (single){
      let first = true;
      for (let i = 0; i < this.state.rows.length; i++) {
        if (this.state.rows[i].isCheck == true){
              if(first){
                first = false;
                this.state.preIndex = i;
              }else{
                this.state.rows[i].isCheck = false;
              }
        }
      }
      //更新dataSource
      this.setState({
        dataSource: ds.cloneWithRows(this.state.rows)
      })
      this._onChoose();
    }

  }

    clear(text){
        this.setState({
            textContent: this.state.initTextContent,
        })
    }

  render() {
    return (

      <View>

        <Modal
          animationType={'slide'}
          transparent={true}
          visible={this.state.show}
          onShow={() => { } }
          onRequestClose={() => this.onRequestClose()} >
          <View style={styles.container}>
            <View style={styles.subView}>

              <Text style={[styles.titleText, this.props.titleTextStyle]}>
                {this.state.titleText}
              </Text>
              <View style={[styles.horizontalLine, this.props.horizontalLineStyle]} />
              
              
              <ListView style={{ height: windowHeight - 200, marginLeft: 5, }}
                dataSource={this.state.dataSource}
                renderRow={this._renderRow}
                />

              <View style={[styles.horizontalLine, this.props.horizontalLineStyle]} />
              <View style={styles.buttonView}>
                <TouchableOpacity underlayColor='transparent'
                  style={styles.buttonStyle}
                  onPress={() => _this._onCancel()}>
                  <Text style={styles.buttonText}>
                    取消
                   </Text>
                </TouchableOpacity>
                <View style={styles.verticalLine} />
                <TouchableOpacity underlayColor='transparent'
                  style={styles.buttonStyle}
                  onPress={() => _this._onChoose()}>
                  <Text style={styles.buttonText}>
                    确定
                   </Text>
                </TouchableOpacity>
              </View>
            </View>
          </View>
        </Modal>
        <TouchableOpacity onPress={() => {
          _this = this;
          _this._onShow()
        } }>
          <View style={[styles.textContentStyle, this.props.textContentStyle]}>
            <Text numberOfLines={1} >{this.state.textContent}</Text>
          </View>
        </TouchableOpacity>
      </View>

    );
  }
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#00000099',
    alignItems: 'center',
    justifyContent: 'center',
    flex: 1,
  },
  // modal上子View的样式  
  subView: {
    marginLeft: 30,
    marginRight: 30,
    backgroundColor: '#ffffff',
    alignSelf: 'stretch',
    justifyContent: 'center',
    borderRadius: 10,
    borderWidth: 0.5,
    borderColor: '#ccc',
  },
  // 标题  
  titleText: {
    marginTop: 5,
    marginBottom: 5,
    fontSize: 16,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  // 水平的分割线  
  horizontalLine: {
    height: 0.5,
    backgroundColor: '#ccc',
  },
  // 按钮  
  buttonView: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  buttonStyle: {
    flex: 1,
    height: 30,
    alignItems: 'center',
    justifyContent: 'center',
  },
  // 竖直的分割线  
  verticalLine: {
    width: 0.5,
    height: 30,
    backgroundColor: '#ccc',
  },
  buttonText: {

    fontSize: 16,
    color: '#3393F2',
    textAlign: 'center',
  },
  textContentStyle: {
    borderWidth: 1,
    borderColor: '#12b7f5',
    borderRadius: 5,
    height: 30,
    justifyContent: 'center',
    alignItems: 'center'
  }
});
